<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-top">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件-->
      <el-table stripe border :data="roleList">
        <el-table-column prop="name" width="200" align="center" label="角色">
          <template v-slot="{row}">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" siez="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" width="200" align="center" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{row}">
            <!-- 开1 关0 -->
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <!-- 判断是否启用-->
            <span v-else>{{ row.state===1 ? "已启用": row.state===0 ? "未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" siez="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditorOk(row)">确认</el-button>
              <el-button size="mini" @click="btnEditorCancel(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnOkey(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="isEdit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>

        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px;">
        <el-pagination
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          :current-page="pageParams.page"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 弹层 -->
    <el-dialog title="新增角色" width="500px" hei :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="form" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini" style="width: 300px;" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- 不需要校验不需要prop -->
          <!-- 重置表单需要prop -->
          <el-switch v-model="roleForm.state" :inactive-value="0" :active-value="1" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" :cols="5" size="mini" style="width: 300px;" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="center">
        <el-col :span="10">
          <el-button type="primary" @click="btnOk">确 定</el-button>
          <el-button @click="btnCancel">取 消</el-button></el-col>
      </el-row>

    </el-dialog>

    <!-- 放置权限弹层 -->
    <el-dialog title="分配权限" width="600px" :visible.sync="showRoleDialog">
      <!-- 展示角色 树形-->
      <!-- 展示空白是字段的问题 -->
      <el-tree
        ref="permTree"
        show-checkbox
        default-expand-all
        :data="treeList"
        :props="{label: 'name'}"
        :default-checked-keys="currtIdList"
        node-key="id"
        check-strictly
      />
      <el-row type="flex" justify="center" style="margin-top: 40px;">
        <el-button size="mini" type="primary" @click="submitOk">确定</el-button>
        <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
      </el-row>
    </el-dialog></div>
</template>
<script>
import { getRoleList, addRole, updateRole, deleteRole, getRoleDetail, assignRole } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { listToTreeDate } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      roleForm: {
        name: '',
        description: '',
        state: '1'// 关闭是0 打开是1
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      showRoleDialog: false,
      treeList: [],
      currtIdList: [],
      currtIds: null,
      roleList: [],
      showDialog: false,
      // 将分页信息放置到一个对象中
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页显示多少条
        total: 0 // 总共多少条
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 添加角色
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      // 赋值数据
      this.roleList = rows
      this.pageParams.total = total
      // 针对每一行数据片加一个编辑状态
      this.roleList.forEach(item => {
        // item.isEdit = false // 设置一个属性 初始值为false
        // 数据响应式的问题 数据变化 视图更新
        // 添加的动态属性不是响应式的
        // this.$set(目标对象, '属性', 初始值) 可以针对目标对象 添加的属性 添加响应式1
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          description: item.description,
          name: item.name,
          state: item.state
        })
      })
    },
    changePage(newPage) {
      // 修改当前页码
      this.pageParams.page = newPage
      // 重新获取数据
      this.getRoleList()
    },
    // 确认按钮
    btnOk() {
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          // 发送请求
          // console.log(this.roleForm)
          await addRole(this.roleForm)
          // 消息提示
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          // 重新获取数据
          this.getRoleList()
          // 关闭弹层
          this.btnCancel()
        }
      })
    },
    // 关闭弹层
    btnCancel() {
      // 关闭弹层
      // 重置表单
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    // 编辑
    isEdit(row) {
      row.isEdit = true // 改变编辑状态
      row.editRow = {
        description: row.description,
        name: row.name,
        state: row.state
      }
    },
    // 编辑确认
    async  btnEditorOk(row) {
      // 校验必填项
      if (row.editRow.name && row.editRow.description) {
        // 编辑赋值
        // 延展运算符
        await updateRole({ ...row.editRow, id: row.id })
        // 消息提示
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
        // 此方法不支持多行编辑
        // 重新获取数据
        // this.getRoleList()

        // 更新显示数据 退出编辑状态
        // Object.assign(row, row.editRow) 目标 来源
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑 状态
        })
      } else {
        this.$message({
          message: '角色和描述不能为空',
          type: 'warning'
        })
      }
    },
    // 编辑取消
    btnEditorCancel(row) {
      row.isEdit = false
      row.editRow = {
        description: row.description,
        name: row.name,
        state: row.state
      }
    },
    // 删除
    async confirmDel(id) {
      // console.log(id)
      await deleteRole(id) // 后端删除
      // 消息提示
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      // 如果删除的数据是最后一条
      if (this.roleList.length === 1) {
        // 如果是第一页
        if (this.pageParams.page === 1) {
          // 不需要再次请求
        } else {
          // 如果不是第一页
          // 页码减1
          this.pageParams.page--
        }
      }
      // 重新获取数据
      this.getRoleList()
    },
    // 分配权限
    async btnOkey(id) {
      const result = await getPermissionList()
      this.treeList = listToTreeDate(result, 0)
      const { permIds } = await getRoleDetail(id)
      this.showRoleDialog = true
      // console.log(id)
      this.currtIds = id
      this.currtIdList = permIds
    },
    async submitOk() {
      await assignRole({
        id: this.currtIds,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message({
        message: '分配权限成功',
        type: 'success'
      })

      this.showRoleDialog = false
    }
  }
}
</script>
<style scoped>
.role-top{
  padding: 10px;
}
.highlight {
  background-color: skyblue;
}
</style>
